/*
 * Main.java
 *
 * Created on 18 novembre 2006, 13:11
 *
 * Copyright (C) 2006-2007 Alexis ROBERT
 * Under the terms of the GPL2 license.
 */

package blbarc;

import java.util.*;
import javax.swing.JOptionPane;

/**
 * Main window class
 * @author  Alexis ROBERT
 */

public class Main extends javax.swing.JFrame {
    private blbarc.Database db;
    private String previousBarcode = ""; // Previous barcode for double scanning
    
    /** Creates new form Main */
    public Main() {
        super();
        initComponents();
        db = new blbarc.Database();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        ScanButton = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        settingsMenuItem = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenu4 = new javax.swing.JMenu();
        Debug1Item = new javax.swing.JMenuItem();
        Debug2Item = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("BLBARC v2");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setLabelFor(jTextField1);
        jLabel1.setText(i18n.getInstance().getString("pleasescan"));

        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextField1KeyPressed(evt);
            }
        });

        ScanButton.setMnemonic(i18n.getInstance().getString("scan_mnemo").charAt(0));
        ScanButton.setText(i18n.getInstance().getString("scan"));
        ScanButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ScanButtonActionPerformed(evt);
            }
        });

        jMenu1.setMnemonic(i18n.getInstance().getString("file_mnemo").charAt(0));
        jMenu1.setText(i18n.getInstance().getString("file"));
        settingsMenuItem.setMnemonic(i18n.getInstance().getString("settingsitem_mnemo").charAt(0));
        settingsMenuItem.setText(i18n.getInstance().getString("settingsitem"));
        settingsMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                settingsMenuItemActionPerformed(evt);
            }
        });

        jMenu1.add(settingsMenuItem);
        settingsMenuItem.getAccessibleContext().setAccessibleParent(jMenu1);

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
        jMenuItem1.setMnemonic(i18n.getInstance().getString("exit_mnemo").charAt(0));
        jMenuItem1.setText(i18n.getInstance().getString("exit"));
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ExitMenu(evt);
            }
        });

        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);
        jMenu1.getAccessibleContext().setAccessibleParent(jMenuBar1);

        jMenu3.setMnemonic(i18n.getInstance().getString("search_mnemo").charAt(0));
        jMenu3.setText(i18n.getInstance().getString("search"));
        jMenuItem3.setMnemonic(i18n.getInstance().getString("showall_mnemo").charAt(0));
        jMenuItem3.setText(i18n.getInstance().getString("showall"));
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });

        jMenu3.add(jMenuItem3);

        jMenuBar1.add(jMenu3);

        jMenu4.setMnemonic('D');
        jMenu4.setText("Debug");
        Debug1Item.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        Debug1Item.setText("Scan 3186320005882");
        Debug1Item.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Debug1ItemActionPerformed(evt);
            }
        });

        jMenu4.add(Debug1Item);

        Debug2Item.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        Debug2Item.setText("Scan 9782744071829");
        Debug2Item.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Debug2ItemActionPerformed(evt);
            }
        });

        jMenu4.add(Debug2Item);

        jMenuBar1.add(jMenu4);

        jMenu2.setMnemonic(i18n.getInstance().getString("help_mnemo").charAt(0));
        jMenu2.setText(i18n.getInstance().getString("help"));
        jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
        jMenuItem2.setMnemonic(i18n.getInstance().getString("help_mnemo").charAt(0));
        jMenuItem2.setText(i18n.getInstance().getString("aboutitem"));
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AboutActionPerformed(evt);
            }
        });

        jMenu2.add(jMenuItem2);
        jMenuItem2.getAccessibleContext().setAccessibleParent(jMenu2);

        jMenuBar1.add(jMenu2);
        jMenu2.getAccessibleContext().setAccessibleParent(jMenuBar1);

        setJMenuBar(jMenuBar1);
        jMenuBar1.getAccessibleContext().setAccessibleName("Menubar");
        jMenuBar1.getAccessibleContext().setAccessibleParent(this);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 487, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .add(jTextField1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 389, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(ScanButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 89, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .add(20, 20, 20))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(ScanButton)
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void Debug2ItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Debug2ItemActionPerformed
        jTextField1.setText("9782744071829");
        jTextField1.grabFocus();
    }//GEN-LAST:event_Debug2ItemActionPerformed

    private void Debug1ItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Debug1ItemActionPerformed
        jTextField1.setText("3186320005882");
        jTextField1.grabFocus();
    }//GEN-LAST:event_Debug1ItemActionPerformed

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
        SearchResultsDialog searchresult = new SearchResultsDialog(this, true, this.db);
        searchresult.fillResults(this.db.getBarcode());
        searchresult.setVisible(true);
    }//GEN-LAST:event_jMenuItem3ActionPerformed

    private void settingsMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_settingsMenuItemActionPerformed
        ConfigDialog cfgdlg = new ConfigDialog(this, true);
        cfgdlg.setVisible(true);
    }//GEN-LAST:event_settingsMenuItemActionPerformed

    private void ExitMenu(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExitMenu
        formWindowClosing(null); // HACK ? :)
        dispose();
    }//GEN-LAST:event_ExitMenu

    private void AboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AboutActionPerformed
        AboutDialog about = new AboutDialog(this, true);
        about.setVisible(true);
    }//GEN-LAST:event_AboutActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        System.out.println("Shutdowning database ...");
        db.shutdown();
    }//GEN-LAST:event_formWindowClosing

    private void ScanButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ScanButtonActionPerformed
        String barcodeTxt = jTextField1.getText();
        if (barcodeTxt.compareTo(this.previousBarcode) == 0) {
            // Double scanned !
            EditForm form = new EditForm(this, true, this.db);
            
            if (!this.db.isBarcode(barcodeTxt)) {
                form.create = true;
                
                Barcode barcodeObj = new Barcode();
                barcodeObj.barcode = barcodeTxt;
                
                if (Configuration.getInstance().getInternet() == true) {
                    try {
                        BCDB bcdbinstance = new BCDB();
                        if (bcdbinstance.isBarcode(barcodeTxt)) {
                            if(JOptionPane.showConfirmDialog(null, i18n.getInstance().getString("bcdbfound_long"), i18n.getInstance().getString("bcdbfound_short"),
                                JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE) == 0) {
                                Barcode distantbarcode = bcdbinstance.getBarcode(barcodeTxt);
                                barcodeObj.title = distantbarcode.title;
                                barcodeObj.fields = distantbarcode.fields;
                            }
                        }
                    } catch (BCDBProtocolMismatch ex) {
                        JOptionPane.showMessageDialog(null, i18n.getInstance().getString("mismatch_long"),
                                i18n.getInstance().getString("mismatch_short"),JOptionPane.ERROR_MESSAGE);
                        System.out.println("BCDBProtocolMismatch : "+ex.toString());
                    } catch (BCDBException ex) {
                        System.out.println("BCDBException : "+ex.toString());
                    }
                }
                barcodeObj.autoFill();
                form.fillData(barcodeObj);
                form.setDeleteVisible(false);
            } else {
                Barcode barcodeObj = this.db.getBarcode(barcodeTxt)[0];
                form.fillData(barcodeObj);
                form.setDeleteVisible(true);
            }
            form.setTitle(i18n.getInstance().getString("showingarticle"));
            form.setVisible(true);
            
            this.jLabel1.setText(i18n.getInstance().getString("pleasescan"));
            this.previousBarcode = "";
        } else {
            int doWeContinue = 0; // BOUUUHHHH ! That's very very very bad !
            if ((!Barcode.verifyCheckDigit(barcodeTxt)) && (Configuration.getInstance().getEAN13CheckDigit())) {
                doWeContinue = JOptionPane.showConfirmDialog(null, i18n.getInstance().getString("checkdigiterror_long"),
                        i18n.getInstance().getString("checkdigiterror_short"), JOptionPane.YES_NO_OPTION);
            }
            
            if (doWeContinue == 0) {
                if (this.db.isBarcode(barcodeTxt)) {
                    Barcode barcodeObj = this.db.getBarcode(barcodeTxt)[0];
                    this.jLabel1.setText(i18n.getInstance().getCompound("articlefound",
                            new Object[]{barcodeObj.title}));
                } else {
                    this.jLabel1.setText(i18n.getInstance().getString("noarticlefound"));
                }
                this.previousBarcode = barcodeTxt;
            }
        }
        this.jTextField1.setText("");
    }//GEN-LAST:event_ScanButtonActionPerformed

    private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            this.ScanButtonActionPerformed(null);
        }
    }//GEN-LAST:event_jTextField1KeyPressed
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem Debug1Item;
    private javax.swing.JMenuItem Debug2Item;
    private javax.swing.JButton ScanButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenu jMenu4;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JMenuItem settingsMenuItem;
    // End of variables declaration//GEN-END:variables
    
}
